package com.wlw.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.wlw.entity.City;
import com.wlw.entity.Gonglue;
import com.wlw.service.CityService;
import com.wlw.service.GonglueService;

import edu.xjsoft.base.orm.support.Page;
import edu.xjsoft.base.orm.support.PropertyFilter;

@Controller
@RequestMapping("/gonglue/*")
public class GonglueAction {
	@Autowired
	private GonglueService gonglueService;
	@Autowired
	private CityService cityService;
	/**
	 * 文件上传
	 * 
	 * @throws IOException
	 */
	@RequestMapping("addGonglue")
	public String addGonglue(Gonglue gonglue,
			@RequestParam MultipartFile myfile, HttpServletRequest request)
			throws IOException {
		String endType = "";
		String city_name = request.getParameter("city_name");
		PropertyFilter filters = new PropertyFilter("name", city_name);
		List<City> city = cityService.search(filters);
		if (city.size()!=0) {
			// root是得到本项目在服务器的路径：“D:\tomcat\apache-tomcat-7.0.52\webapps\tourGonglue\”
			String root = request.getSession().getServletContext().getRealPath("/");
			// getCanonicalFile()方法是返回路径名的规范形式。
			File uploadDir = new File(root, "foreground/tourGonglue_files/gonglue")
					.getCanonicalFile();
			if (!uploadDir.exists() || uploadDir.isFile()) {
				uploadDir.mkdir();
			}
			//设置攻略属性：
			Gonglue gonglue2 = new Gonglue();
			gonglue2.setBrowserCount(0);
			gonglue2.setDownloadCount(0);
			Date date = new Date();
			gonglue2.setTime(date.toLocaleString());
			gonglue2.setZanCount(0);
			System.out.println(city.get(0).getName());
			if (city.size() != 0) {
				//设置与城市关联：
				//gonglue2.setId(city.get(0).getId());
				gonglue2.setCity(city.get(0));
				// 如果选择了上传的文件
				if (!myfile.isEmpty()) {
					String name1 = myfile.getName();
					String name2 = myfile.getOriginalFilename();
					String type = myfile.getContentType();
					long length = myfile.getSize();
					// 得到要上传文件的后缀名
					endType = name2.substring(name2.lastIndexOf("."),name2.length());
					gonglue2.setContent("/" + city_name + endType);
					System.out.println(gonglue2.getId()+":"+gonglue2.getContent()+","+gonglue2.getTime()+","+gonglue2.getCity().getName());
					gonglueService.save(gonglue2);
					
					System.out.println(name1);
					System.out.println(name2);
					System.out.println(type);
					System.out.println(endType);
					System.out.println("文件大小：" + length + " 字节");
					// 处理小文件：
					// myfile.transferTo(new File(uploadDir, name2));
					// 处理大文件：
					InputStream is = myfile.getInputStream();
					FileOutputStream fos = new FileOutputStream(new File(uploadDir,
							city_name + endType));
					System.out.println(city_name+endType);
					byte[] b = new byte[1024];
					int len = 0;
					while ((len = is.read(b)) > 0) {
						fos.write(b, 0, len);
					}
					fos.flush();
					fos.close();
					is.close();
				}
				return "background/success";
			}
		}
		return "background/failure";
	}
	
	//攻略下载：
	@RequestMapping("download")
	public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String root = request.getSession().getServletContext().getRealPath("/");
		File uploadDir = new File(root, "/foreground/tourGonglue_files/gonglue/").getCanonicalFile();
		System.out.println(uploadDir);
		int id = Integer.parseInt(request.getParameter("id"));
		PropertyFilter filters = new PropertyFilter("id", id);
		List<Gonglue> gonglues = gonglueService.search(filters);
		int downloadCount = gonglues.get(0).getDownloadCount()+1;
		gonglues.get(0).setDownloadCount(downloadCount);
		int browserCount = gonglues.get(0).getBrowserCount()+1;
		gonglues.get(0).setBrowserCount(browserCount);
		int zanCount = gonglues.get(0).getZanCount()+1;
		gonglues.get(0).setZanCount(zanCount);
		gonglueService.saveOrUpdate(gonglues.get(0));
		System.out.println("下载量："+downloadCount);
		String fname = gonglues.get(0).getContent();
		//文件下载, 需要设置response相关的头信息
		//要对response设置头部信息
		File file = new File(uploadDir, fname);	
		System.out.println(file.exists());
		response.resetBuffer();
		fname = new String(fname.getBytes("GBK"), "ISO8859-1");  //解决中文乱码，是GBK不是UTF-8
		response.addHeader("Content-Disposition", "attachment;filename=" + fname);
		response.addHeader("Content-Length", file.length()+"");
		response.setContentType("application/octet-stream"); //设置某类型，让浏览不能直接打开
		InputStream is = new FileInputStream(file);
		OutputStream os = response.getOutputStream();
		byte[] b = new byte[1024];
		int len = 0;
		while ((len = is.read(b)) > 0) {
			os.write(b, 0, len);
		}
		os.flush();
		os.close();
		is.close();
		
	}
	
	@RequestMapping("modGonglue")
	public String modGonglue(HttpServletRequest req,Model model){
		int id = Integer.parseInt(req.getParameter("id"));
		PropertyFilter filters = new PropertyFilter("id", id);
		List<Gonglue> gonglues = gonglueService.search(filters);
		model.addAttribute("gonglues", gonglues);
		return "background/modGonglue";
	}
	@RequestMapping("modifyGonglue")
	public String modifyGonglue(HttpServletRequest req){
		int id = Integer.parseInt(req.getParameter("id"));
		PropertyFilter filters = new PropertyFilter("id", id);
		List<Gonglue> gonglues = gonglueService.search(filters);
		gonglues.get(0).setBrowserCount(Integer.parseInt(req.getParameter("browserCount")));
		gonglues.get(0).setDownloadCount(Integer.parseInt(req.getParameter("downloadCount")));
		gonglues.get(0).setZanCount(Integer.parseInt(req.getParameter("zanCount")));
		String time = new Date().toLocaleString();
		gonglues.get(0).setTime(time);
		gonglueService.saveOrUpdate(gonglues.get(0));
		return "background/success";
	}
	@RequestMapping("delGonglue")
	public String delGonglue(HttpServletRequest req){
		int id = Integer.parseInt(req.getParameter("id"));
		gonglueService.remove(id);
		return "background/successDel";
	}
	
	@RequestMapping("{pageNo}")
	public String list(@PathVariable int pageNo,Model model){
		Page<Gonglue> page = new Page<Gonglue>(5);
		page.setPageNo(pageNo);
		gonglueService.loadAll(page);
		model.addAttribute("page", page);
		return "background/findGonglue";
	}
	
	//返回热门推荐攻略：
	@RequestMapping("hotGonglues")
	public String hotGonglues(Model model){
		List<Gonglue> hotGonglues = gonglueService.hotGonglues();
		model.addAttribute("hotGonglues", hotGonglues);
		return "foreground/index";
	}
	
}
